package com.myspring.web.exceptions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myspring.web.exceptions.exModel.AjaxBusinessException;
import com.myspring.web.exceptions.exModel.BusinessException;
import com.myspring.web.exceptions.exModel.LocalRuntimeException;
import com.myspring.web.exceptions.exModel.MutiException;
import com.myspring.web.exceptions.exModel.NestedException;

/**
 * SimpleMappingExceptionResolver spring默认异常处理器
 */
@Controller
@RequestMapping("/exception")
public class ExceptionController {
	
	@Autowired
	private UserService userService;
	
	//==============================非运行时异常测试===============================
	@RequestMapping(value="/init", method={RequestMethod.GET, RequestMethod.POST})
	public String init() {
		return "/exception/view";
	}
	
	@RequestMapping(value="/super", method={RequestMethod.GET, RequestMethod.POST})
	public String superException() throws Exception {
//		throw new IllegalArgumentException("非法参数错误");
		try {
			userService.save();
		} catch (Exception e) {
			System.out.println("被捕获的异常：" + e);
			throw e;
		}
		return "/exception/super";
	}
	
	@RequestMapping(value="/globalView")
	public String globalView(BusinessException businessException) throws BusinessException {
		throw new BusinessException("view");
	}
	
	/**
	 * ajax json测试
	 * @param ex
	 * @return
	 * @throws AjaxBusinessException
	 */
	@RequestMapping(value="/globalJson")
	@ResponseBody
	public String globalJson(AjaxBusinessException ex) throws AjaxBusinessException {
		throw new AjaxBusinessException("json");
	}
	
	/**
	 * 内嵌异常测试
	 * @return
	 * @throws NestedException
	 */
	@RequestMapping(value="/nested")
	public String nestedException() throws NestedException {
		throw new NestedException(new BusinessException("this is BusinessException"));
	}
	
	/**
	 * JDK7多个异常捕获测试
	 * @return
	 * @throws MutiException
	 */
	@RequestMapping(value="/muti")
	public String mutiNestedException() throws MutiException {
//		try {
//			String s = null;
//			s.concat("");
//			throw new BusinessException();
//		} catch(BusinessException | NullPointerException ex) {
//			throw new MutiException(ex);
//		}
		return null;
	}
	
	//================================运行时异常测试==================================
	@RequestMapping("/local")
	public String local() {
		throw new LocalRuntimeException("LocalException");
	}
	
	@ExceptionHandler
	@ResponseBody
	public ExceptionMessage handleLocal(LocalRuntimeException ex) {
		ExceptionMessage em = new ExceptionMessage();
		em.setCode("local");
		em.setMessage(ex.getMessage());
		return em;
	}
	
	
}
